  <template>
    <div class="home-page">
      <div class="funtion-pael">
        <el-tabs tab-position="left" class="vertical-tabs" v-model="activeTab">
          <el-tab-pane v-for="(tab, index) in tabs" :key="index">
            <template #label>
              <div class="tab-label">
                <i :class="tab.icon"></i>
                <span>{{ tab.label }}</span>
              </div>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="material-panel">
        <component :is="tabs[activeTab].component" ref="dynamicComponentRef" />
      </div>
      <div class="canvas-panel">
        <div class="nav-bar">
          <div class="stage-name" v-if="!isEditingName" @click="  ">
            <span class="name">{{ stageName }}</span>
            <span class="scene-text">-配置场景</span>
            <i class="el-icon-edit"></i>
          </div>
          <div class="stage-name-edit" v-else>
            <el-input v-model="stageName" size="small" ref="nameInput" @blur="finishEditingName"
              @keyup.enter="finishEditingName"></el-input>
          </div>
          <div class="action-buttons">
            <el-button-group>
              <el-button size="small" icon="el-icon-back" title="撤销"></el-button>
              <el-button size="small" icon="el-icon-right" title="前进"></el-button>
            </el-button-group>
          </div>
          <div class="right-buttons">
            <el-button type="text" class="normal-btn">预览</el-button>
            <el-button type="text" class="normal-btn">保存</el-button>
            <el-button type="text" class="publish-btn">发布</el-button>
          </div>
        </div>
        <div class="canvas-container">
          <div id="canvas" class="main-canvas"></div>
        </div>
        <div class="add-panel">
          <div class="preview-list">
            <div class="preview-item" v-for="(canvas, index) in canvasList" :key="index" 
                 :class="{ active: currentIndex === index }"
                 @click="switchCanvas(index)">
              <div class="preview-content">
                <div class="thumbnail" ref="thumbnailRefs"></div>
              </div>
              <div class="preview-title">{{ canvas.name || `画布 ${index + 1}` }}</div>
            </div>
          </div>
          <div class="add-btn" @click="addNewCanvas">
            <i class="el-icon-plus"></i>
          </div>
        </div>
      </div>
    </div>
  </template>

<script>
import { KonvaJs } from './utils/konva';
import ImagePanel from './components/ImagePanel.vue';
import ToolPanel from './components/ToolPanel.vue';
import TemplatePanel from './components/TemplatePanel.vue';
import BackgroundPanel from './components/BackgroundPanel.vue';
import ElementPanel from './components/ElementPanel.vue';
import LayerPanel from './components/LayerPanel.vue';
import AdjustPanel from './components/AdjustPanel.vue';
import CanvasBoard from './components/CanvasBoard.vue';

export default {
  name: 'HomePage',
  components: {
    ImagePanel,
    ToolPanel,
    TemplatePanel,
    BackgroundPanel,
    ElementPanel,
    LayerPanel,
    AdjustPanel,
    CanvasBoard
  },
  data() {
    return {
      konva: new KonvaJs('canvas'),
      activeTab: '3',
      canvasList: [{
        name: '画布 1',
        height: 800,
        y: 0
      }],
      currentIndex: 0,
      thumbnailRefs: [],
      previewStages: {},
      previewLayers: {},
      canvasGap: 50,
      currentScrollY: 0,
      scrollSpeed: 20,
      stageName: '舞台名称',
      isEditingName: false,
      tabs: [
        { label: '图片', icon: 'el-icon-picture-outline', component: 'ImagePanel' },
        { label: '工具', icon: 'el-icon-s-operation', component: 'ToolPanel' },
        { label: '模板', icon: 'el-icon-document', component: 'TemplatePanel' },
        { label: '背景', icon: 'el-icon-picture', component: 'BackgroundPanel' },
        { label: '元素', icon: 'el-icon-s-grid', component: 'ElementPanel' },
        { label: '图层', icon: 'el-icon-menu', component: 'LayerPanel' },
        { label: '调整', icon: 'el-icon-setting', component: 'AdjustPanel' }
      ]
    };
  },
  mounted() {
    // 初始化 Konva
    this.konva.init();
    this.listenStageEvents();
    
    // 初始化第一个画布
    this.updateThumbnails();
  },
  methods: {
    listenStageEvents() {
      const { stage } = this.konva;
      if (!stage) return
      const container = stage.container();

      container.addEventListener('dragover', (e) => {
        e.preventDefault()
      })

      container.addEventListener('drop', (e) => {
        e.preventDefault()
        stage.setPointersPositions(e);
        const childComponent = this.$refs.dynamicComponentRef; // 获取当前激活的组件
        if (childComponent) {
          const shape = this.konva.drawShapes(childComponent.state.type, stage.getRelativePointerPosition())
          if (!shape) return
        }


      })


    },
    addNewCanvas() {
      const lastCanvas = this.canvasList[this.canvasList.length - 1];
      const newY = lastCanvas.y + lastCanvas.height + this.canvasGap;
      
      const newCanvas = {
        name: `画布 ${this.canvasList.length + 1}`,
        height: this.canvasList[0].height,
        y: newY
      };
      
      // 添加新图层
      const newLayer = this.konva.addLayer(newY);
      
      this.canvasList.push(newCanvas);
      this.currentIndex = this.canvasList.length - 1;
      
      // 更新舞台高度
      const totalHeight = newY + newCanvas.height;
      this.konva.stage.height(totalHeight);
      
      // 更新缩略图
      this.$nextTick(() => {
        this.updateThumbnails();
      });
    },
    
    switchCanvas(index) {
      if (index === this.currentIndex) return;
      this.currentIndex = index;
      
      // 切换到对应的图层
      this.konva.setCurrentLayer(index);
      
      // 滚动到选中的画布位置
      const canvas = this.canvasList[index];
      const container = this.konva.stage.container();
      container.scrollTo({
        top: canvas.y,
        behavior: 'smooth'
      });
      
      // 更新缩略图
      this.$nextTick(() => {
        this.updateThumbnails();
      });
    },
    
    updateThumbnails() {
      this.canvasList.forEach((canvas, index) => {
        const thumbnailRef = this.$refs.thumbnailRefs[index];
        if (thumbnailRef) {
          // 清空缩略图容器
          thumbnailRef.innerHTML = '';
          
          // 创建临时舞台用于生成缩略图
          const tempStage = new Konva.Stage({
            container: thumbnailRef,
            width: 120,
            height: 80
          });
          
          const tempLayer = new Konva.Layer();
          tempStage.add(tempLayer);
          
          // 获取当前画布区域的内容
          const stage = this.konva.stage;
          const layer = this.konva.currentLayer;
          
          // 创建临时画布来截取当前画布区域
          const tempCanvas = document.createElement('canvas');
          tempCanvas.width = 120;
          tempCanvas.height = 80;
          const tempCtx = tempCanvas.getContext('2d');
          
          // 绘制背景
          tempCtx.fillStyle = '#f5f5f5';
          tempCtx.fillRect(0, 0, 120, 80);
          
          // 绘制当前画布内容
          const scale = 120 / stage.width();
          tempCtx.scale(scale, scale);
          tempCtx.drawImage(
            stage.toCanvas(),
            0,
            canvas.y,
            stage.width(),
            canvas.height,
            0,
            0,
            stage.width(),
            canvas.height
          );
          
          // 创建缩略图
          const img = document.createElement('img');
          img.src = tempCanvas.toDataURL();
          img.style.width = '100%';
          img.style.height = '100%';
          img.style.objectFit = 'contain';
          thumbnailRef.appendChild(img);
          
          // 清理临时舞台
          tempStage.destroy();
        }
      });
    },
    finishEditingName() {
      this.isEditingName = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.home-page {
  width: 100%;
  height: 100vh;
  display: flex;
  background-color: #f5f5f5;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;

  .funtion-pael {
    width: 100px;
    height: 100%;
    background-color: #fff;
    box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .vertical-tabs {
      width: 100%;
      height: 100%;

      :deep(.el-tabs__header) {
        margin: 0;
        width: 100%;
        height: 100%;
      }

      :deep(.el-tabs__nav) {
        width: 100%;
        height: 100%;
      }

      :deep(.el-tabs__nav-wrap) {
        width: 100%;
        height: 100%;
      }

      :deep(.el-tabs__item) {
        width: 100%;
        height: calc(100% / 7);
        line-height: 1.2;
        padding: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
        transition: background-color 0.3s;

        &:hover {
          background-color: rgba(0, 0, 0, 0.05);
        }

        &.is-active {
          background-color: rgba(0, 0, 0, 0.1);
        }

        .tab-label {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;

          i {
            font-size: 24px;
            margin-bottom: 4px;
          }

          span {
            font-size: 12px;
          }
        }
      }

      :deep(.el-tabs__active-bar) {
        display: none;
      }
    }
  }

  .material-panel {
    width: 250px;
    height: 100%;
    background-color: #fff;
    box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
    overflow-y: auto;
  }

  .canvas-panel {
    width: calc(100% - 350px);
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .nav-bar {
      height: 60px;
      background-color: #fff;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      padding: 0 20px;

      .stage-name {
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;

        .name {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100px;
        }

        .scene-text {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
          white-space: nowrap;
          flex-shrink: 0;
        }

        i {
          font-size: 14px;
          color: #909399;
          transition: color 0.3s;
          flex-shrink: 0;
        }

        &:hover {
          i {
            color: #409eff;
          }
        }
      }

      .stage-name-edit {
        width: 100px;

        :deep(.el-input__inner) {
          height: 32px;
          line-height: 32px;
          font-size: 16px;
          font-weight: 500;
        }
      }

      .action-buttons {
        margin-left: 20px;

        :deep(.el-button-group) {
          .el-button {
            padding: 6px 12px;

            i {
              font-size: 16px;
            }
          }
        }
      }

      .right-buttons {
        margin-left: auto;
        display: flex;
        align-items: center;
        gap: 8px;

        :deep(.el-button) {
          padding: 8px 12px;
          font-size: 14px;
        }

        .normal-btn {
          border: 1px solid #303133;
          border-radius: 4px;
          color: #303133;

          &:hover {
            color: #303133;
            border-color: #303133;
            background-color: rgba(0, 0, 0, 0.05);
          }
        }

        .publish-btn {
          background-color: #409eff;
          color: #fff;
          border-radius: 4px;

          &:hover {
            background-color: #66b1ff;
            color: #fff;
          }
        }
      }
    }

    .canvas-container {
      flex: 1;
      overflow-y: auto;
      position: relative;
      cursor: grab;
      width: 100%;
      height: 100%;

      &:active {
        cursor: grabbing;
      }

      #canvas {
        width: 100%;
        height: 100%;
        position: relative;
      }

      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 8px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 4px;

        &:hover {
          background: #555;
        }
      }
    }

    .add-panel {
      height: 90px;
      background-color: #fff;
      box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      padding: 0 20px;

      .preview-list {
        display: flex;
        gap: 10px;
        margin-right: 20px;
        overflow-x: auto;
        flex: 1;

        .preview-item {
          position: relative;
          cursor: pointer;
          flex-shrink: 0;

          &.active {
            .preview-content {
              border-color: #409eff;
            }
          }

          .preview-content {
            width: 120px;
            height: 80px;
            border: 2px solid #dcdfe6;
            border-radius: 4px;
            overflow: hidden;
            position: relative;

            .thumbnail {
              width: 100%;
              height: 100%;

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
          }

          .preview-title {
            font-size: 12px;
            color: #606266;
            text-align: center;
            margin-top: 4px;
          }
        }
      }

      .add-btn {
        width: 40px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #409eff;
        color: #fff;
        border-radius: 50%;
        cursor: pointer;
        transition: all 0.3s;
        flex-shrink: 0;

        &:hover {
          background: #66b1ff;
        }

        i {
          font-size: 20px;
        }
      }
    }
  }
}
</style>